package com.ycxh.plugin;

import org.apache.ibatis.jdbc.SQL;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;

import java.sql.DatabaseMetaData;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据库方言
 * mysql、oracle、sqlserver
 */
public class Dialect {

    /**
     * 不同数据库是不同的分页方式
     */
    public static BoundSql getBoundSql(MappedStatement ms, Integer offSet, BoundSql boundSql, String paramKey) throws Exception {
        // 获取数据库类型
        DatabaseMetaData metaData = ms.getConfiguration().getEnvironment().getDataSource().getConnection().getMetaData();
        // 判断当前数据库类型是mysql还是oracle https://www.ngui.cc/el/696537.html?action=onClick
        // String databaseType = metaData.getDatabaseProductVersion();
        String databaseType = metaData.getDatabaseProductName();

        String sql = null;
        if (databaseType.equalsIgnoreCase("MySQL")) {
            // 采用MySQL分页
            sql = getMySQLPage(boundSql.getSql(), offSet);
        } else if (databaseType.equalsIgnoreCase("Oracle")) {

        }

        List<ParameterMapping> parameterMappings = new ArrayList(boundSql.getParameterMappings());
        if (offSet > 0) {
            parameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), paramKey + "offSet", Integer.class).build());
            parameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), paramKey + "pageRow", Integer.class).build());
        } else {
            parameterMappings.add(new ParameterMapping.Builder(ms.getConfiguration(), paramKey + "pageRow", Integer.class).build());
        }

        BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), sql, parameterMappings, boundSql.getParameterObject());

        return newBoundSql;
    }

    private static String getMySQLPage(String initSQL, int offSet) {
        // 拼预编译语句
        // select * from account limit 1,10
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(initSQL);

        if (offSet > 0) {
            stringBuilder.append(" limit ?, ?");
        } else {
            stringBuilder.append(" limit ?");
        }

        return stringBuilder.toString();
    }

}
